package com.ie.controller;

import com.ie.common.http.Result;
import com.ie.common.http.ResultCodeEnum;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
public class FileUploadController {

    // 获取运行时目录路径
    private final Path rootLocation = Paths.get("").toAbsolutePath().normalize();

    @PostMapping("/upload")
    public Result handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 创建上传目录（如果不存在）
            Path uploadDir = rootLocation.resolve("upload-dir");
            Files.createDirectories(uploadDir);

            // 生成带时间戳的文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String originalFilename = file.getOriginalFilename();
            String newFilename = timestamp + "_" + originalFilename;

            // 保存文件
            Path targetLocation = uploadDir.resolve(newFilename);
            Files.copy(file.getInputStream(), targetLocation);

            // 返回保存路径
            String savedPath = targetLocation.toString();
            return Result.build(null, ResultCodeEnum.SUCCESS.getCode(), savedPath);

        } catch (IOException ex) {
            return Result.build(null, ResultCodeEnum.DATA_ERROR);
        }
    }
}
